package com.mobinters.image;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class SDcardManager {
	  private File cacheDir;
	  private Context context;
	  String rootPath;
	  public final static String APP_PATH_SD_CARD = "/ChupAnhHanQuoc/";
	  public final static String APP_THUMBNAIL_PATH_SD_CARD = "thumbnails";
	  private final static int IMAGE_MAX_SIZE=100;
/**
 * Construtor
 * @param context
 */
	  public SDcardManager(Context context){
	       this.context=context;
	       rootPath=android.os.Environment.getExternalStorageDirectory().toString();//-->/mnt/sdcard/
	    }
/**
 * createFolder with folderName
 * @param folderName
 * @Note:Instrution function.
 * cacheDir=context.getCacheDir();-->create a file with path:"/data/data/com.example.signaturescreen/cache"
 * cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),folderName);--->create a file with path:"/mnt/sdcard/Hung Cop"
 * cacheDir.mkdirs():create folder 
 */
	    public void createFolder(String folderName)
	    {   
	    	 //Find the dir to save cached images. Check the Media access to the File
	        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
	        {   cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),folderName);// Tao 1 File voi path=Eviroment..getExternalStorageDirectory()+ folderName
	           // Log.d("FolderPath", "Folder Path is"+cacheDir.toString());//Folder Path is "/mnt/sdcard/Hung Cop"

	        } else{ cacheDir=context.getCacheDir();//Returns the absolute path to the application specific cache directory on the filesystem
	          //Log.e("Folder", "Folder Path is"+cacheDir.toString());//Folder Path is "/data/data/com.example.signaturescreen/cache"

	               }
	        //----If the File has'nt created yet,create it.
	        if(!cacheDir.exists()){cacheDir.mkdirs();}//Creates the directory named by the trailing filename of this file, including the complete directory path required to create this directory.
	        //else Toast.makeText(context, "The File has existed!",Toast.LENGTH_SHORT).show();
		 }
/**
 * @category: use to save a file to a folder in SD card    
 * @param folderPath
 * @param file
 */
	    public boolean saveBitmapToExternalStorage(Bitmap image,String folderName,String imageName) {
	    	String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/" +folderName;
	    	//Toast.makeText(context, "The File path is!" + fullPath,Toast.LENGTH_SHORT).show();
	    	try {
	    	File dir = new File(fullPath);//-->create a file path
	    	if (!dir.exists()) {
	    	dir.mkdirs();//create a file in its path
	    	Log.d("File Saved",dir.toString()+" is created!");
	    	}

	    	OutputStream fOut = null;
	    	File file = new File(fullPath, imageName+".png");
	    	file.createNewFile();
	    	fOut = new FileOutputStream(file);

	    	// 100 means no compression, the lower you go, the stronger the compression
	    	image.compress(Bitmap.CompressFormat.PNG, 85, fOut);//100
	    	fOut.flush();
	    	fOut.close();

	    	MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

	    	return true;

	    	} catch (Exception e) {
	    	//Log.e("saveToExternalStorage()", e.getMessage());
	    	return false;
	    	}
	    	}
/**
 * @category: getFile from SD card
 * @param url
 * @return File
 */
    public File getFile(String url){
	        //I identify images by hashcode. Not a perfect solution, good for the demo.
	        String filename=String.valueOf(url.hashCode());
	        File f = new File(cacheDir, filename);
	        return f;
	        
	    }
    public Bitmap getBitmap(String filePath){
    	Bitmap bmp=null;

    	String path = Environment.getExternalStorageDirectory()+filePath+".png";
    	File f = new File(path);
    	if(f.exists()){
    		bmp= BitmapFactory.decodeFile(f.getAbsolutePath());   
    	}
    	else{
    		//Toast.makeText(context,"Can't find the image",Toast.LENGTH_SHORT).show();
    		//crash when happen because other thread call the Toast???
    	}
    	return bmp;
    }
    
    public Bitmap decodeFile(File f){
    	
        //FileOutputStream os = null;
        Bitmap b=null;
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            FileInputStream fis = new FileInputStream(f);
            BitmapFactory.decodeStream(fis, null, o);
            fis.close();

            int scale = 1;
            if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
            }

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            fis = new FileInputStream(f);
            try {

            b = BitmapFactory.decodeStream(fis, null, o2);

            } catch (OutOfMemoryError e) {
                Log.d("hai","filename"+f);
                System.gc();
            }
            fis.close();
        } catch (IOException e) {
        }
        return b;
    }
    
    public ArrayList<Bitmap> getBitmaps(String folderName){
    	return null;
    }
    
    public boolean deleteBitmap(String filePath){
    	String path = Environment.getExternalStorageDirectory()+filePath;
    	File f = new File(path);
    	return f.delete();
    }
/**
 * @category:clear all file
 * 
 */
	    public void clear(){
	        File[] files=cacheDir.listFiles();
	        for(File f:files)
	            f.delete();
	    }
}
